<!--用户管理-->
<template>
    <el-form :model="dictform" ref="dictref" :inline="true" style="text-align: left;">
        <el-form-item label="用户账户" prop="User_account">
            <el-input placeholder="请输入用户账户" v-model="dictform.User_account"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="User_name">
            <el-input placeholder="请输入用户姓名" v-model="dictform.User_name"></el-input>
        </el-form-item>
        <el-form-item label="岗位名称" prop="Position_id">
            <el-select v-model="dictform.Position_id" placeholder="请选择" style="width:180px">
                <el-option
                    v-for="item in positiondata"
                    :key="item.position_id"
                    :label="item.position_name"
                    :value="item.position_id"
                />
            </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="User_status">
            <el-select placeholder="请选择" v-model="dictform.User_status" style="width:200px">
                <el-option :value="0" label="启用"></el-option>
                <el-option :value="1" label="禁用"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="drawer = true">添加</el-button>
        <el-button @click="DeleteAll">删除</el-button>
        <el-button @click="GetEnable">启用</el-button>
        <el-button @click="GetDeactivated">停用</el-button>
    </div>
    <!--表格-->
    <el-table :data="displayData" style="margin-top: 10px;" @selection-change="SelectChange" ref="tableRef">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="user_id" label="序号"></el-table-column>
        <el-table-column prop="user_account" label="用户账号"></el-table-column>
        <el-table-column prop="user_name" label="用户姓名"></el-table-column>
        <el-table-column prop="user_sex" label="性别"></el-table-column>
        <el-table-column prop="user_phone" label="手机号"></el-table-column>
        <el-table-column prop="position_name" label="岗位名称"></el-table-column> <!-- 修改 -->
        <el-table-column prop="department_name" label="所在部门"></el-table-column> <!-- 修改 -->
        <el-table-column prop="roles" label="角色"></el-table-column> <!-- 修改 -->
        <el-table-column prop="user_sort" label="排序"></el-table-column>
        <el-table-column prop="user_status" label="状态">
            <template #default="scope">
                {{ scope.row.user_status === 0 ? '启用' : '停用' }}
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="155px">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row.user_id)">编辑</el-button>
                <el-button type="danger" text="删除" @click="deletiondata(scope.row.user_id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

    <!-- 添加抽屉 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">添加</h4>
        </template>
        <template #default>
            <el-form :model="addform" ref="addformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-row :gutter="20">
                    <!-- 左侧列 -->
                    <el-col :span="12">
                        <el-form-item label="用户账号" prop="User_account">
                            <el-input placeholder="请输入" v-model="addform.User_account"></el-input>
                        </el-form-item>
                        <el-form-item label="用户密码" prop="User_password">
                            <el-input placeholder="请输入" v-model="addform.User_password"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="User_sex">
                            <el-select placeholder="请选择" v-model="addform.User_sex" style="width:200px">
                                <el-option value="男" label="男"></el-option>
                                <el-option value="女" label="女"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="岗位名称" prop="Position_id">
                            <el-select v-model="addform.Position_id" placeholder="请选择" style="width:180px">
                                <el-option
                                    v-for="item in positiondata"
                                    :key="item.position_id"
                                    :label="item.position_name"
                                    :value="item.position_id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="状态" prop="Position_status">
                            <el-radio-group v-model="addform.User_status">
                                <el-radio :value="0">启用</el-radio>
                                <el-radio :value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 右侧列 -->
                    <el-col :span="12">
                        <el-form-item label="用户姓名" prop="User_name">
                            <el-input placeholder="请输入" v-model="addform.User_name"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="User_phone">
                            <el-input placeholder="请输入" v-model="addform.User_phone"></el-input>
                        </el-form-item>
                        <el-form-item label="所属部门" prop="Department_id">
                            <el-select v-model="addform.Department_id" placeholder="请选择" style="width:180px">
                                <el-option
                                    v-for="item in departmentdata"
                                    :key="item.department_id"
                                    :label="item.department_name"
                                    :value="item.department_id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="排序" prop="User_sort">
                            <el-input placeholder="请输入" v-model="addform.User_sort"></el-input>
                        </el-form-item>
                    </el-col>

                    <!-- 角色控件 -->
                    <el-col :span="24">
                        <el-form-item label="角色" prop="RoleNames">
                            <el-input 
                            placeholder="请选择角色" 
                            v-model="addform.RoleNames"
                            readonly
                            style="width: 100%;"
                            >
                            <!-- 右侧图标按钮 -->
                            <template #append>
                                <el-button @click="openRoleDialog">
                                <el-icon><More /></el-icon>
                                </el-button>
                            </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <!-- 备注横跨两列 -->
                    <el-col :span="24">
                        <el-form-item label="备注" prop="Remark">
                            <el-input type="textarea" placeholder="请输入" v-model="addform.Remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="Add">保存</el-button>
            </div>
        </template>
    </el-drawer>
    
    <!-- 角色选择弹窗（添加时使用） -->
    <el-dialog v-model="roleDialogVisible" title="选择角色" width="700px">
    <!-- 添加搜索框 -->
    <div style="margin-bottom: 15px;">
        <el-input
        v-model="addRoleFilter"
        placeholder="搜索角色名称"
        clearable
        @input="handleAddRoleFilter"
        style="width: 200px;"
        >
        <template #prefix>
            <el-icon><Search /></el-icon>
        </template>
        </el-input>
    </div>
    
    <el-table 
        :data="filteredRolesForAdd" 
        height="400px"
        @row-click="handleRoleRowClick"
        @selection-change="handleSelectionChange"
        ref="roleTableRef"
        >
        <el-table-column prop="role_name" label="角色名称"></el-table-column>
        <!-- 修改这一行 -->
        <el-table-column 
            type="selection" 
            width="55" 
            :selectable="checkAddSelectable">
        </el-table-column>
    </el-table>
    
    <template #footer>
        <div style="text-align: right;">
        <el-button @click="confirmSelect">确定</el-button>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        </div>
    </template>
    </el-dialog>

    <!-- 修改抽屉 -->
    <el-drawer v-model="drawer2">
        <template #header>
            <h4 style="text-align: left;">修改</h4>
        </template>
        <template #default>
            <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-row :gutter="20">
                    <!-- 左侧列 -->
                    <el-col :span="12">
                        <el-form-item label="用户账号" prop="User_account">
                            <el-input placeholder="请输入" v-model="updateform.User_account"></el-input>
                        </el-form-item>
                        <el-form-item label="用户密码" prop="User_password">
                            <el-input placeholder="请输入" v-model="updateform.User_password"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="User_sex">
                            <el-select placeholder="请选择" v-model="updateform.User_sex" style="width:200px">
                                <el-option value="男" label="男"></el-option>
                                <el-option value="女" label="女"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="岗位名称" prop="Position_id">
                            <el-select v-model="updateform.Position_id" placeholder="请选择" style="width:180px">
                                <el-option
                                    v-for="item in positiondata"
                                    :key="item.position_id"
                                    :label="item.position_name"
                                    :value="item.position_id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="状态" prop="Position_status">
                            <el-radio-group v-model="updateform.User_status">
                                <el-radio :value="0">启用</el-radio>
                                <el-radio :value="1">停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    
                    <!-- 右侧列 -->
                    <el-col :span="12">
                        <el-form-item label="用户姓名" prop="User_name">
                            <el-input placeholder="请输入" v-model="updateform.User_name"></el-input>
                        </el-form-item>
                        <el-form-item label="手机号" prop="User_phone">
                            <el-input placeholder="请输入" v-model="updateform.User_phone"></el-input>
                        </el-form-item>
                        <el-form-item label="所属部门" prop="Department_id">
                            <el-select v-model="updateform.Department_id" placeholder="请选择" style="width:180px">
                                <el-option
                                    v-for="item in departmentdata"
                                    :key="item.department_id"
                                    :label="item.department_name"
                                    :value="item.department_id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="排序" prop="User_sort">
                            <el-input placeholder="请输入" v-model="updateform.User_sort"></el-input>
                        </el-form-item>
                    </el-col>

                    <!-- 修改后的角色控件 -->
                    <el-col :span="24">
                        <el-form-item label="角色" prop="RoleName">
                            <el-input 
                            placeholder="请选择角色" 
                            v-model="updateform.RoleName"
                            readonly
                            style="width: 100%;"
                            >
                            <!-- 右侧图标按钮 -->
                            <template #append>
                                <el-button @click="openEditRoleDialog">
                                <el-icon><More /></el-icon>
                                </el-button>
                            </template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <!-- 备注横跨两列 -->
                    <el-col :span="24">
                        <el-form-item label="备注" prop="Remark">
                            <el-input type="textarea" placeholder="请输入" v-model="updateform.Remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer2 = false">取消</el-button>
                <el-button type="primary" @click="Update">保存</el-button>
            </div>
        </template>
    </el-drawer>

    <!-- 角色选择弹窗（修改时使用） -->
    <el-dialog v-model="editRoleDialogVisible" title="选择角色" width="700px">
        <!-- 添加搜索框 -->
        <div style="margin-bottom: 15px;">
            <el-input
            v-model="editRoleFilter"
            placeholder="搜索角色名称"
            clearable
            @input="handleEditRoleFilter"
            style="width: 200px;"
            >
            <template #prefix>
                <el-icon><Search /></el-icon>
            </template>
            </el-input>
        </div>
        
        <el-table 
            :data="filteredRolesForEdit" 
            height="400px"
            @row-click="handleEditRoleRowClick"
            @selection-change="handleEditSelectionChange"
            ref="editRoleTableRef"
            >
            <el-table-column prop="role_name" label="角色名称"></el-table-column>
            <!-- 修改这一行 -->
            <el-table-column 
                type="selection" 
                width="55" 
                :selectable="checkEditSelectable">
            </el-table-column>
        </el-table>
        
        <template #footer>
            <div style="text-align: right;">
            <el-button @click="confirmEditSelect">确定</el-button>
            <el-button @click="editRoleDialogVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox } from 'element-plus'; //提示信息
import * as XLSX from 'xlsx';
import { useRouter } from 'vue-router';//路由
import { More,Search } from '@element-plus/icons-vue'
export default {
setup()
    {
        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        const rules = reactive({
            User_account: [
                { required: true, message: '用户账号不能为空', trigger: 'blur' }
            ],
            User_password: [
                { required: true, message: '用户密码不能为空', trigger: 'blur' }
            ],
            User_name: [
                { required: true, message: '用户姓名不能为空', trigger: 'blur' }
            ],
            User_sex: [
                { required: true, message: '请选择性别', trigger: 'change' }
            ],
            User_phone: [
                { required: true, message: '手机号不能为空', trigger: 'blur' }
            ],
            Position_id: [
                { required: true, message: '请选择岗位名称', trigger: 'change' }
            ],
            Department_id: [
                { required: true, message: '请选择所属部门', trigger: 'change' }
            ],
            User_status: [
                { required: true, message: '请选择状态', trigger: 'change' }
            ],
            User_sort: [
                { required: true, message: '排序不能为空', trigger: 'blur' }
            ],
            RoleNames: [
                {
                validator: (rule, value, callback) => {
                    if (addform.Role_id.length === 0) {
                    callback(new Error('请选择至少一个角色'));
                    } else {
                    callback();
                    }
                },
                trigger: 'change'
                }
            ],
            RoleName: [
                {
                validator: (rule, value, callback) => {
                    if (updateform.Role_id.length === 0) {
                    callback(new Error('请选择至少一个角色'));
                    } else {
                    callback();
                    }
                },
                trigger: 'change'
                }
            ]
        });

        //#region 查询

        //表单
        const dictref = ref("");
        const dictform = reactive({
            User_account:"",
            User_name:"",
            Position_id:null,
            User_status:null
        })
        //表格数据
        const dictdata = ref([]);
        //部门
        const departmentdata = ref([]);
        //岗位
        const positiondata = ref([]);
        //角色
        const Roledata = ref([]);
        //用户角色联系
        const userRoledata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function Reset() {
            dictref.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            currentPage.value = 1;
            All();
        }

        // 查询数据
        function All() {
            http.get("/User/GetCondition", {
                params: {
                    CurrentPage: currentPage.value,
                    User_account: dictform.User_account,
                    User_name: dictform.User_name,
                    Position_id: dictform.Position_id,
                    User_status: dictform.User_status
                }
            }).then(res => {
                rows.value = res.data.rows; // 总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    });
                }
                dictdata.value = res.data.list;
                console.log("dictdata:", dictdata); // 调试用
            }).catch(err => {
                console.log(err);
            });
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }
        //查询部门
        function GetDepartment() {
            http.get("/Supplier/GetDepartment", {
                params: {
                    Department_id: name
                }
            }).then(res => {
                console.log("API数据:", res.data); // 调试用
                departmentdata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        //查询岗位
        function GetPosition() {
            http.get("/Position/GetAll").then(res => {
                console.log("岗位:", res.data); // 调试用
                positiondata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        //查询角色
        function GetRole() {
            http.get("/Role/GetAll").then(res => {
                console.log("角色:", res.data); // 调试用
                Roledata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('数据加载失败');
            });
        }
        //用户角色联系
        function GetUserRole() {
            http.get("/UserRole/GetAllUserRoles").then(res => {
                console.log("用户角色:", res.data); // 调试用
                userRoledata.value = res.data; // 将查询结果赋值给 Departmentdata
            }).catch(err => {
                console.log(err);
                ElMessage.error('用户角色数据加载失败');
            });
        }

        // 在 setup() 中添加
        const displayData = computed(() => {
            if (!departmentdata.value.length || !positiondata.value.length || !userRoledata.value.length) {
                return []; // 基础数据未加载时返回空数组
            }
            
            return dictdata.value.map(user => {
                // 查找部门名称
                const department = departmentdata.value.find(
                dep => dep.department_id === user.department_id
                );
                
                // 查找岗位名称
                const position = positiondata.value.find(
                pos => pos.Position_id === user.Position_id
                );
                
                // 查找并拼接角色名称
                const roles = userRoledata.value
                .filter(role => role.user_id === user.user_id)
                .map(role => role.roleNames)
                .join(', ');
                
                return {
                ...user,
                department_name: department?.department_name || '未知部门',
                position_name: position?.position_name || '未知岗位',
                roles: roles || '无角色'
                };
            });
        });
        //#endregion


        //#region 添加

        //添加抽屉
        const drawer = ref(false);

        const addformref = ref();
        //添加表单
        const addform = reactive({
            User_account:"",
            User_password:"",
            User_name:"",
            User_sex:"",
            User_phone:"",
            Position_id:null,
            Department_id:null,
            User_status:0,
            User_sort:"",
            Remark:"",
            Role_id:[],
            RoleName:[]
        })
       
        // 添加数据
        async function Add() {
            addformref.value.validate(async (valid) => {
                if (!valid) {
                    // 验证不通过时不执行添加操作
                    ElMessage.warning('请正确填写表单');
                    return;
                }
                try {
                    const adddata = {
                        RoleIds: addform.Role_id,
                        editUserDto:{
                            User_account:addform.User_account,
                            User_password:addform.User_password,
                            User_name:addform.User_name,
                            User_sex:addform.User_sex,
                            User_phone:addform.User_phone,
                            Position_id:addform.Position_id,
                            Department_id:addform.Department_id,
                            User_status:addform.User_status,
                            User_sort:addform.User_sort,
                            Remark:addform.Remark
                        }
                    };

                    const response = await http.post("/User/GetAdd", adddata);

                    if (response.data > 0) {
                        ElMessage({
                            message: '添加成功.',
                            type: 'success',
                        });
                        await All();
                        await GetUserRole();
                        // 清除表单
                        addformref.value?.resetFields();
                        drawer.value=false;
                    }
                } catch (err) {
                    console.log(err);
                }
            });
        }

        const checkAddSelectable = (row, index) => {
            // 如果已经选中了3个角色
            if (addform.Role_id.length >= 3) {
                // 只有已经被选中的角色行的复选框才可操作（例如取消选中）
                // 其他角色行的复选框将被设置为 disabled
                return addform.Role_id.includes(row.role_id);
            }
            // 如果选中的角色少于3个，所有行的复选框都可选
            return true;
        };
        //#endregion


        //#region 修改

        //修改抽屉
        const drawer2=ref(false);
        // 修改表单
        const updateformref = ref();
        const updateform = reactive({
            User_id: "",
            User_account: "",
            User_password: "",
            User_name: "",
            User_sex: "",
            User_phone: "",
            Position_id: null,
            Department_id: null,
            User_status: 0,
            User_sort: "",
            Remark: "",
            Role_id: [],    // 角色ID数组
            RoleName: []    // 角色名称数组
        })

        // 显示修改
        function ShowUpdate(id) {
            drawer2.value = true;
            
            // 根据当前id查询用户基本信息
            http.get("/User/GetID?id=" + id)
            .then(userRes => {
                // 填充用户基本信息
                updateform.User_id = id;
                updateform.User_account = userRes.data.user_account;
                updateform.User_password = userRes.data.user_password;
                updateform.User_name = userRes.data.user_name;
                updateform.User_sex = userRes.data.user_sex;
                updateform.User_phone = userRes.data.user_phone;
                updateform.Position_id = userRes.data.position_id;
                updateform.Department_id = userRes.data.department_id;
                updateform.User_status = userRes.data.user_status;
                updateform.User_sort = userRes.data.user_sort;
                updateform.Remark = userRes.data.remark;
                
                // 获取用户角色信息
                return http.get("/UserRole/Getuid?uid=" + id);
                })
                .then(roleRes => {
                    // 填充角色信息
                    if (roleRes.data) {
                        updateform.Role_id = roleRes.data.roleIds || [];
                        updateform.RoleName = roleRes.data.roleNames || [];
                    }
                })
                .catch(err => {
                    console.error("获取用户或角色信息失败:", err);
                    // 这里可以添加错误提示，例如使用Element Plus的ElMessage
                    ElMessage.error("获取用户信息失败: " + (err.response?.data?.message || err.message));
                });
        }
        //修改
        async function Update() {
            updateformref.value.validate(async (valid) => {
                if (!valid) {
                ElMessage.warning('请正确填写表单');
                return;
                }

                const updatedata = {
                RoleIds: updateform.Role_id,
                editUserDto: {
                    User_id: updateform.User_id,
                    User_account: updateform.User_account,
                    User_password: updateform.User_password,
                    User_name: updateform.User_name,
                    User_sex: updateform.User_sex,
                    User_phone: updateform.User_phone,
                    Position_id: updateform.Position_id,
                    Department_id: updateform.Department_id,
                    User_status: updateform.User_status,
                    User_sort: updateform.User_sort,
                    Remark: updateform.Remark
                }
                };

                try {
                const res = await http.put("/User/GetEdit", updatedata);
                if (res.data > 0) {
                    ElMessage({
                    message: '修改成功.',
                    type: 'success'
                    });
                    await All();
                    await GetUserRole();
                    drawer2.value = false;
                }
                } catch (err) {
                console.error(err);
                }
            });
        }

        const checkEditSelectable = (row, index) => {
            // 如果已经选中了3个角色
            if (updateform.Role_id.length >= 3) {
                // 只有已经被选中的角色行的复选框才可操作（例如取消选中）
                // 其他角色行的复选框将被设置为 disabled
                return updateform.Role_id.includes(row.role_id);
            }
            // 如果选中的角色少于3个，所有行的复选框都可选
            return true;
        };
        //#endregion

        //region 删除，启用，停用
        // 删除方法
        const tableRef = ref(null); // 添加表格引用
        function deletiondata(id) {
            ElMessageBox.confirm('确定要删除该岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                // 调用后端逻辑删除接口（PUT 方法）
                const res = await http.put('/User/GetDelete?id='+id);

                if (res.status === 200) {
                    ElMessage.success('删除成功');
                    All();
                }
                } catch (err) {
                    ElMessage.error('删除失败');
                    console.error(err);
                }
            }).catch(() => {
                // 用户取消操作
            });
        }

        // 批量删除
        function DeleteAll() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要删除的数据');
                return;
            }
            
            ElMessageBox.confirm('确定要删除选中的岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromises = selectdata.value.map(item => {
                    return http.put(`/User/GetDelete?id=${item.user_id}`);
                });
                
                Promise.all(deletePromises)
                    .then(results => {
                        const successCount = results.filter(res => res.data > 0).length;
                        if (successCount === selectdata.value.length) {
                            ElMessage.success(`成功删除 ${successCount} 条数据`);
                        } else {
                            ElMessage.warning(`成功删除 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                        }
                        All(); // 刷新数据
                        tableRef.value.clearSelection(); // 清空选中状态
                    })
                    .catch(err => {
                        console.error(err);
                        ElMessage.error('删除失败');
                    });
            }).catch(() => {
                ElMessage.warning('已取消删除');
                return;
            });
        }
        
        // 批量停用
        function GetDeactivated() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要停用的数据');
                return;
            }
            
            ElMessageBox.confirm('确定要停用选中的岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromises = selectdata.value.map(item => {
                    return http.put(`/User/GetDeactivated?id=${item.user_id}`);
                });
                
                Promise.all(deletePromises)
                    .then(results => {
                        const successCount = results.filter(res => res.data > 0).length;
                        if (successCount === selectdata.value.length) {
                            ElMessage.success(`成功停用 ${successCount} 条数据`);
                        } else {
                            ElMessage.warning(`成功停用 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                        }
                        All(); // 刷新数据
                        tableRef.value.clearSelection(); // 清空选中状态
                    })
                    .catch(err => {
                        console.error(err);
                        ElMessage.error('停用失败');
                    });
            }).catch(() => {
                ElMessage.warning('已取消停用');
                return;
            });
        }
        
        // 批量启用
        function GetEnable() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要启用的数据');
                return;
            }
            
            ElMessageBox.confirm('确定要启用选中的岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const deletePromises = selectdata.value.map(item => {
                    return http.put(`/User/GetEnable?id=${item.user_id}`);
                });
                
                Promise.all(deletePromises)
                    .then(results => {
                        const successCount = results.filter(res => res.data > 0).length;
                        if (successCount === selectdata.value.length) {
                            ElMessage.success(`成功启用 ${successCount} 条数据`);
                        } else {
                            ElMessage.warning(`成功启用 ${successCount} 条，失败 ${selectdata.value.length - successCount} 条`);
                        }
                        All(); // 刷新数据
                        tableRef.value.clearSelection(); // 清空选中状态
                    })
                    .catch(err => {
                        console.error(err);
                        ElMessage.error('启用失败');
                    });
            }).catch(() => {
                ElMessage.warning('已取消启用');
                return;
            });
        }
        //#endregion

        onMounted(async () => {
        try {
            // 先加载基础数据
            await GetDepartment();
            await GetPosition();
            await GetUserRole(); 
            GetRole()
            All();
        } catch (error) {
            console.error('初始化失败:', error);
        }
        });
        
        // 控制角色弹窗显示
        const roleDialogVisible = ref(false);

        // 选中的角色列表
        const selectedRoles = ref([]);

        // 打开角色弹窗
        function openRoleDialog() {
        roleDialogVisible.value = true;
        // 清空已选（可选：保留上次选择）
        selectedRoles.value = [];
        addRoleFilter.value = '';
        }

        // 处理多选变化
        function handleSelectionChange(selection) {
            // 如果因为 selectable 的限制，selection.length 实际上不会超过 3
            // 但为了健壮性，可以保留检查（虽然可能不会触发）
            if (selection.length > 3) {
                ElMessage.warning('最多只能选择3个角色');
                // 同步表单数据为前3个（理论上不会发生）
                addform.Role_id = selection.slice(0, 3).map(r => r.role_id);
                addform.RoleNames = selection.slice(0, 3).map(item => item.role_name).join(", ");
                return; // 不继续执行
            }
            // 正常同步数据
            addform.Role_id = selection.map(r => r.role_id);
            addform.RoleNames = selection.map(item => item.role_name).join(", ");
        }

        // 确认选择
        function confirmSelect() {
            // 修复点：改为检查addform中的角色ID
            if (addform.Role_id.length === 0) {
                ElMessage.warning('请至少选择一个角色');
                return;
            }
            
            roleDialogVisible.value = false;
        }

        // 表格引用
        const roleTableRef = ref(null);

        // 点击行切换选中状态
        function handleRoleRowClick(row) {
            if (!roleTableRef.value) return;

            const currentSelection = roleTableRef.value.getSelectionRows();
            const isSelected = currentSelection.some(item => item.role_id === row.role_id);

            if (isSelected) {
                // 已选中，取消选中
                roleTableRef.value.toggleRowSelection(row, false);
            } else {
                // 未选中，需要检查是否可以选择（是否超过限制或是否被 selectable 禁用）
                // 1. 检查是否已达到选择上限
                if (currentSelection.length >= 3) {
                    ElMessage.warning('最多只能选择3个角色');
                    return;
                }
                // 2. 检查该行是否被 selectable 函数允许选择
                //    这一步实际上是可选的，因为如果 selectable 返回 false，
                //    toggleRowSelection 通常不会有效果。但显式检查更安全。
                if (checkAddSelectable(row)) {
                    roleTableRef.value.toggleRowSelection(row, true);
                } else {
                    // 理论上不应该到达这里，因为行是禁用的，但作为后备
                    ElMessage.info('该角色当前不可选择');
                }
            }
        }

        // 控制修改时的角色弹窗显示
        const editRoleDialogVisible = ref(false);
        // 修改时选中的角色列表
        const selectedEditRoles = ref([]);
        // 修改时的角色表格引用
        const editRoleTableRef = ref(null);

        // 打开修改时的角色弹窗
        function openEditRoleDialog() {
            editRoleFilter.value = '';
            editRoleDialogVisible.value = true;
            // 清空已选（可选：保留上次选择）
            selectedEditRoles.value = [];
            // 回显已选角色
            if (updateform.Role_id?.length > 0) {
                // 延迟执行以确保表格渲染完成
                setTimeout(() => {
                updateform.Role_id.forEach(roleId => {
                    const role = Roledata.value.find(r => r.role_id === roleId);
                    if (role) {
                        editRoleTableRef.value.toggleRowSelection(role, true);
                    }
                });
                }, 100);
            }
        }

        // 处理修改时角色表格的多选变化
        function handleEditSelectionChange(selection) {
            if (selection.length > 3) {
                ElMessage.warning('最多只能选择3个角色');
                updateform.Role_id = selection.slice(0, 3).map(r => r.role_id); // 更新了 updateform
                updateform.RoleName = selection.slice(0, 3).map(item => item.role_name).join(", "); // 更新了 updateform
                return;
            }
            updateform.Role_id = selection.map(r => r.role_id); // 更新了 updateform
            updateform.RoleName = selection.map(item => item.role_name).join(", "); // 更新了 updateform
        }

        // 确认修改时的选择
        function confirmEditSelect() {
            if (updateform.Role_id.length === 0) {
                ElMessage.warning('请至少选择一个角色');
                return;
            }
            editRoleDialogVisible.value = false;
        }

        // 点击行切换选中状态（修改时）
        function handleEditRoleRowClick(row) {
            if (!editRoleTableRef.value) return;

            const currentSelection = editRoleTableRef.value.getSelectionRows();
            const isSelected = currentSelection.some(item => item.role_id === row.role_id);

            if (isSelected) {
                // 已选中，取消选中
                editRoleTableRef.value.toggleRowSelection(row, false);
            } else {
                // 未选中，需要检查是否可以选择（是否超过限制或是否被 selectable 禁用）
                // 1. 检查是否已达到选择上限
                if (currentSelection.length >= 3) {
                    ElMessage.warning('最多只能选择3个角色');
                    return;
                }
                // 2. 检查该行是否被 selectable 函数允许选择
                if (checkEditSelectable(row)) {
                    editRoleTableRef.value.toggleRowSelection(row, true);
                } else {
                    // 理论上不应该到达这里，因为行是禁用的，但作为后备
                    ElMessage.info('该角色当前不可选择');
                }
            }
        }

        // 监听添加抽屉的关闭
        watch(() => drawer.value, (newVal, oldVal) => {
        if (oldVal && !newVal) { // 从打开状态变为关闭状态
            // 重置添加表单
            if (addformref.value) {
            addformref.value.resetFields();
            }
            // 清空角色选择
            addform.Role_id = [];
            addform.RoleNames = '';
            // 清空角色选择状态
            if (roleTableRef.value) {
            roleTableRef.value.clearSelection();
            }
        }
        });

        // 监听修改抽屉的关闭
        watch(() => drawer2.value, (newVal, oldVal) => {
        if (oldVal && !newVal) { // 从打开状态变为关闭状态
            // 重置修改表单
            if (updateformref.value) {
            updateformref.value.resetFields();
            }
            // 清空角色选择
            updateform.Role_id = [];
            updateform.RoleNames = '';
            // 清空角色选择状态
            if (editRoleTableRef.value) {
            editRoleTableRef.value.clearSelection();
            }
        }
        });

        // 角色过滤相关变量
        const addRoleFilter = ref(''); // 添加表单的角色过滤条件
        const editRoleFilter = ref(''); // 修改表单的角色过滤条件

        // 添加表单的角色过滤列表
        const filteredRolesForAdd = computed(() => {
        if (!addRoleFilter.value) return Roledata.value;
        return Roledata.value.filter(item => 
            item.role_name.includes(addRoleFilter.value)
        );
        });

        // 修改表单的角色过滤列表
        const filteredRolesForEdit = computed(() => {
        if (!editRoleFilter.value) return Roledata.value;
        return Roledata.value.filter(item => 
            item.role_name.includes(editRoleFilter.value)
        );
        });

        // 添加表单的角色过滤处理
        function handleAddRoleFilter() {
        // 过滤时保持之前的选中状态
        nextTick(() => {
            if (roleTableRef.value) {
            addform.Role_id.forEach(roleId => {
                const role = Roledata.value.find(r => r.role_id === roleId);
                if (role) {
                roleTableRef.value.toggleRowSelection(role, true);
                }
            });
            }
        });
        }

        // 修改表单的角色过滤处理
        function handleEditRoleFilter() {
        // 过滤时保持之前的选中状态
        nextTick(() => {
            if (editRoleTableRef.value) {
            updateform.Role_id.forEach(roleId => {
                const role = Roledata.value.find(r => r.role_id === roleId);
                if (role) {
                editRoleTableRef.value.toggleRowSelection(role, true);
                }
            });
            }
        });
        }

        return{
            checkAddSelectable,
            checkEditSelectable,
            rules,
            addRoleFilter,
            editRoleFilter,
            filteredRolesForAdd,
            filteredRolesForEdit,
            handleAddRoleFilter,
            handleEditRoleFilter,
            Search,
            editRoleDialogVisible,
            openEditRoleDialog,
            handleEditSelectionChange,
            confirmEditSelect,
            handleEditRoleRowClick,
            editRoleTableRef,
            roleTableRef,
            handleRoleRowClick,
            roleDialogVisible,
            openRoleDialog,
            confirmSelect,
            handleSelectionChange,
            More,
            Roledata,
            departmentdata,
            positiondata,
            displayData,
            GetDeactivated,
            GetEnable,
            tableRef,
            deletiondata,
            DeleteAll,
            SelectChange,
            formatDateTime,
            user,
            dictref,
            dictform,
            dictdata,
            rows,
            currentPage,
            dateFormat,
            Reset,
            Search,
            All,
            handlePageChange,
            drawer,
            addform,
            addformref,
            Add,
            drawer2,
            updateform,
            updateformref,
            ShowUpdate,
            Update,
            DeleteAll,
            router
        }

    }
}
</script>

<style scoped>

</style>